import { apiUrl }                         from         '@/api/url';
import { compare,accAdd,countNum,formatDate,accMul }   from '@/workers/util/util';

let socket = null;                  // socket连接
let pingCount = 0;                  // ping次数
let pongCount = 0;                  // pong次数
let pingPongTimer = null;           // pingPong定时器
let connectTimer = null;            // 连接过程定时器
let type = '';                      // 当前合约类型
let token = '';
let uid = '';
let lang = '';
let baseTimeout = 10*1000;          // ws连接超时时间
let onLine = true;                  // 当前是否连接网络

let pageStatus = true;              // 页面是否展示在前台
let router = '';                    // 当前页面路由

// setTimeout(()=>{
//     postMessage({
//         type:'noticeInfo',
//         value:{
//             content:'这是内容这是内容',
//             notice_type:'',
//             notice_title:'',
//             msg_type:'trade_notice',
//             order_time:+new Date(),
//             link:'flutterApp://KlineMainChartPage?login=0&InstrumentID=BTCUSDT&type=SwapU',
//             title:'这是标题',
//         }
//     })
// },3000)

function calc(ev){
    if(ev.data === 'pong'){
        pongCount++;
    } else { 
        let res = JSON.parse(ev.data);
        if(res && typeof res === 'object' && res.channel === 'dc_trade_notice'){
            postMessage({
                type:'noticeInfo',
                value:{
                    content:res.data.content,
                    notice_type:res.data.notice_type,
                    notice_title:res.data.notice_title,
                    msg_type:res.data.msg_type,
                    order_time:res.data.order_time,
                    link:res.data.link,
                    title:res.data.title,
                }
            })
        }
    }
}

function checkPingPong(){
    // 检测pingPong是否异常(连接是否异常)
    if(pingCount - pongCount >= 2 && pageStatus){
        pingCount = 0;
        pongCount = 0;
        clearInterval(pingPongTimer);
        clearTimeout(connectTimer);
        if(socket) socket.close();
        socket = null;
        setTimeout(()=>{
            wsConnect().then(res => {
                console.log('重连')
            })
        },3000)
    }
}

function sendPing(){
    // 发送ping
    if(!pageStatus) return
    wsConnect().then(function(){
        socket.send('ping');
        pingCount++;
        checkPingPong();
    })
}

function wsConnect(){
    // 连接socket操作
    return new Promise(resolve => {
        // console.log(socket)
        if(socket && socket.readyState === 1){
            // socket连接正常
            resolve();
            return
        }
        if(socket && socket.readyState != 1){
            // 连接异常
            socket.close();
            setTimeout(() => {
                connect();
            },600)
        }
        if(!socket) connect();
        function connect(){
            clearInterval(pingPongTimer);
            clearTimeout(connectTimer);
            socket = new WebSocket(apiUrl.gameWs+'?token='+token+'&platform=pc');
            socket.onopen = function(){
                // console.log('连接成功')
                //连接成功
                pingCount = 0;
                pongCount = 0;
                initSend();
                clearInterval(pingPongTimer);
                clearTimeout(connectTimer);
                pingPongTimer = setInterval(()=>{
                    sendPing();
                },5000)
                resolve();
            }
            socket.onmessage = calc;
            socket.onerror = function(err){
                
            }
            // 延迟检测是否连接成功
            connectTimer = setTimeout(()=>{
                socket.close();
                setTimeout(() => {
                    connect();
                },600)
            },baseTimeout)
        }
    })
}

function initSend(){
    socket.send(JSON.stringify({
        channel: 'dc_trade_notice',
        account: uid,
        action:'1'
    }))
}

function closeWs(){
    setTimeout(()=>{
        pingCount = 0;
        pongCount = 0;
        clearInterval(pingPongTimer);
        clearTimeout(connectTimer);
        if(socket) socket.close();
        socket = null;
    },600)
}

self.addEventListener('message', function (e) {
    let res = e.data;
    if(typeof res === 'object' && res.type === 'noticeInfo'){
        type = res.type;
        if(res.action === 'sendTokenUid'){
            token = res.value.token;
            uid = res.value.uid;
            lang = res.value.lang;
            wsConnect().then(function(){
                
            })
        }
    }
    if(typeof res === 'object' && res.type === 'SwapSpot'){
        if(res.action === 'pageStatus'){
            console.log(res.value,'.............')
            // 页面是否显示在前台
            let currentPageStatus = res.value === 'show'?true:false;
            if(pageStatus && !currentPageStatus){
                // 从前台返回到后台
                closeWs();
            }
            if(!pageStatus && currentPageStatus && uid){
                // 从后台返回前台
                wsConnect().then(res => {
                    
                })
            }
            pageStatus = currentPageStatus;
        }
    }
}, false);